package us.sunrisemorning.pixivbrower.utils;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;

import javax.sql.DataSource;

import com.jfinal.plugin.activerecord.generator.ColumnMeta;
import com.jfinal.plugin.activerecord.generator.MetaBuilder;
import com.jfinal.plugin.activerecord.generator.TableMeta;

public class MyMetaBuilder extends MetaBuilder {

    public MyMetaBuilder(DataSource dataSource) {
        super(dataSource);
    }

    @Override
    protected void buildColumnMetas(TableMeta tableMeta) throws SQLException {
        String sql = dialect.forTableBuilderDoBuild(tableMeta.name);
        Statement stm = conn.createStatement();
        ResultSet rs = stm.executeQuery(sql);
        ResultSetMetaData rsmd = rs.getMetaData();

        for (int i = 1; i <= rsmd.getColumnCount(); i++) {
            ColumnMeta cm = new ColumnMeta();
            cm.name = rsmd.getColumnName(i);

            String typeStr = null;
            int type = rsmd.getColumnType(i);

            switch (type) {
            case Types.INTEGER:
                typeStr = Integer.class.getName();
                break;
            case Types.VARCHAR:
                typeStr = String.class.getName();
                break;
            default:
                typeStr = String.class.getName();
            }

            cm.javaType = typeStr;

            // 构造字段对应的属性名 attrName
            cm.attrName = buildAttrName(cm.name);

            tableMeta.columnMetas.add(cm);
        }

        rs.close();
        stm.close();
    }
}
